﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.BussLogic;
using TimKen.App;
using System.Data;
using System.Text;
using TimKen.DataEntity;
using System.IO;

namespace TimKen.Web
{
    public partial class Product : TimKen.App.WebPage
    {
        public ProductManager productManager = new ProductManager();
        FavoriteManager frm = new FavoriteManager();
        public string parentLink;
        

        /// <summary>
        /// 分类ID
        /// </summary>
        public int CategoryID
        {
            get
            {
                if (ViewState["CategoryID"] != null)
                    return Convert.ToInt32(ViewState["CategoryID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["CategoryID"] = value;
            }
        }

        /// <summary>
        /// 品牌ID
        /// </summary>
        public int brandID
        {
            get
            {
                if (ViewState["brandID"] != null)
                    return Convert.ToInt32(ViewState["brandID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["brandID"] = value;
            }
        }
        /// <summary>
        /// 行业ID
        /// </summary>
        public int IndustryID
        {
            get
            {
                if (ViewState["IndustryID"] != null)
                    return Convert.ToInt32(ViewState["IndustryID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["IndustryID"] = value;
            }
        }


        public string OptionIDValueWhere
        {
            get
            {
                if (ViewState["OptionIDValueWhere"] != null)
                    return ViewState["OptionIDValueWhere"].ToString();
                else
                    return "";
            }
            set
            {
                ViewState["OptionIDValueWhere"] = value;
            }
        }
        public DataRowCollection drcBrand;      

        private void BindBrandList()
        {
            //品牌
            PBrandManager pbm = new PBrandManager();
            DataSet dsBrand = pbm.GetList(" WHERE  BrandID!=4");
            drcBrand = dsBrand.Tables[0].Rows;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //绑定品牌列表
                BindBrandList();
                if (Request.QueryString["CategoryID"] != null)
                {
                    CategoryID = int.Parse(Request.QueryString["CategoryID"]);
                }

                if (Request.QueryString["IndustryID"] != null)
                    IndustryID = int.Parse(Request.QueryString["IndustryID"]);

                if (Request["feedfdf"] != null)
                {
                    OptionIDValueWhere = Request["feedfdf"];
                }
                ///进行数据验证
                checkStrValid(Request["KeyWords"]);
                checkStrValid(Request["Desc"]);

                /**********************/
                string innhtml = "";
                if (Request["BrandID"] != null && Request["BrandID"].ToString() != "")
                {
                    foreach (System.Data.DataRow dr in drcBrand)
                    {
                        if (dr["BrandID"].ToString() == Request["BrandID"].ToString())
                        {
                            span_typespan.InnerText = dr["Name"].ToString();
                            innhtml += "<code>" + dr["Name"] + "</code>&nbsp;&nbsp;";
                        }
                    }
                }
                if (Request["Desc"] != null && Request["Desc"].ToString() != "")
                {
                    if (innhtml != "")
                        innhtml += "+&nbsp;&nbsp;";
                    innhtml += "<code>" + Request["Desc"] + "</code>&nbsp;&nbsp;";
                }
                if (Request["KeyWords"] != null && Request["KeyWords"].ToString() != "")
                {
                    if (innhtml != "")
                        innhtml += "+&nbsp;&nbsp;";
                    innhtml += "<code>" + Request["KeyWords"] + "</code>&nbsp;&nbsp;";
                }
                span_searchCondition.InnerHtml = innhtml;
                /**********************/
                //绑定数据
                BindData();
                BindResources();

                if (string.IsNullOrEmpty(Request.QueryString["brandid"]) || !TypeParse.IsNumeric(Request.QueryString["brandid"]))
                {
                    brandID = 0;
                }
                else
                    brandID = int.Parse(Request.QueryString["brandid"]);

            }
            if (CategoryID != 0)
            {
                PCategoryManager pcm = new PCategoryManager();
                parentLink = GetParentLink(pcm.GetAllParent(CategoryID, LanguageID));
            }
        }

        private void BindData()
        {
            DataSet ds = new DataSet();

            int brandID = 0;

            if (Request["BrandID"] != null)   
                brandID = TypeParse.StrToInt(Request["BrandID"], 0);    

            //通过关键字,品牌搜索
            if (Request.QueryString["type"] == "1")
            {

                string keywords = Request["KeyWords"];
                string desc = Request["Desc"];

                ds = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, brandID, -1,
                                            keywords, "", desc, false, true, IndustryID);
            }
            //查看分类产品列表
            else if (Request.QueryString["type"] == "2")
            {
                CategoryID = CategoryID == 0 ? -1 : CategoryID;
                ds = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, brandID,
                                            CategoryID, "", "", "", false, true, IndustryID);
            }
            else
            {
                string where = string.IsNullOrEmpty(OptionIDValueWhere)
                                   ? OptionIDValueWhere
                                   : Tools.Decrypt(OptionIDValueWhere);
                ds = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, brandID, CategoryID, "", where, false, true, IndustryID);
            }

            divdh.InnerHtml = GetCategoryListSite(CategoryID, brandID);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0]["total"]);
            span_sizespan.InnerText = AspNetPager1.RecordCount.ToString();
            if (AspNetPager1.RecordCount == 0)
                this.ltEmptyData.Visible = true;
            this.MyRepeater.DataSource = ds.Tables[0].DefaultView;
            this.MyRepeater.DataBind();
        }

        private string GetParentLink(string linkData)
        {
            string[] links = linkData.Split(',');
            StringBuilder sb = new StringBuilder();
            if (links.Length > 0)
            {
                sb.Append("<a href=\"Category.aspx?\">" + GetLangString("ProductCategories") + "</a>&nbsp;—&nbsp;");


                for (int i = 0; i < links.Length; i++)
                {
                    string link = links[i];
                    string[] nameid = link.Split(':');

                    if (nameid.Length == 2 && i != links.Length - 1)
                    {
                        sb.Append("<a href=\"ChildCategory.aspx?cid=" + nameid[1] + "&brandid=" + brandID + "\">" + nameid[0] + "</a>&nbsp;—&nbsp;");
                    }
                    else
                    {
                        sb.Append(nameid[0] + "&nbsp;—&nbsp;");
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 7, 7);
            }
            return sb.ToString();
        }

        public string GetParentLink(int categoryID)
        {
            PCategoryManager pcm = new PCategoryManager();
            string linkData = pcm.GetAllParent(categoryID, LanguageID);
            string[] links = linkData.Split(',');
            StringBuilder sb = new StringBuilder();
            if (links.Length > 0)
            {
                foreach (string link in links)
                {
                    string[] nameid = link.Split(':');
                    if (nameid.Length == 2)
                    {
                        sb.Append("<a href=\"Category.aspx?cid=" + nameid[1] + "\">" + nameid[0] + "</a>: ");
                    }
                    else
                    {
                        sb.Append(nameid[0]);
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 2, 2);
            }
            return sb.ToString();
        }

        public string GetCategoryImage(int categoryID)
        {
            PCategoryManager pcm = new PCategoryManager();
            return pcm.GetCategoryImage(categoryID);
        }

        protected void BindResources()
        {
            this.ltEmptyData.Text = GetLangString("EmptyData");
            this.AspNetPager1.SubmitButtonText = GetLangString("Go");
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void MyRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "AddToShoppingCart")
            {
                UserS u = Session["User"] as UserS;
                //如果用户未登陆，则跳转到注册页面
                if (u == null)
                    Response.Redirect("/User/Register.aspx");
                if (u.UserType == UserType.SelfRegistered)
                {
                    Response.Redirect("/ErrorAuthority.aspx");
                }
                else
                {
                    ImageButton lb = (ImageButton)e.CommandSource;
                    TextBox t = lb.Parent.Controls[4] as TextBox;
                    decimal number = 50;
                    if (!decimal.TryParse(t.Text, out number) || number <= 0)
                    {
                        Alert(GetLangString("InValidNumber"));
                        return;
                    }
                    //ShoppingCartManager scm = new ShoppingCartManager();
                    //ShoppingCart model = new ShoppingCart();
                    int productID = int.Parse(e.CommandArgument.ToString());
                    if (GetProductBasePrice(productID).Price == 0)
                    {
                        Alert(GetLangString("Price0Product"));
                        return;
                    }
                    //model.UserName = CurrentUserName;
                    //model.Number = number;
                    //model.ProductID = productID;
                    //scm.Add(model);
                    //BindData();

                    //Top top = this.Page.Master.FindControl("Top1") as Top;
                    //top.totalCartCount = top.totalCartCount + number;
                    /*
                     * 田勇的新购物车添加方法
                     * */
                    TimKen.DataEntity.Product pr = productManager.GetModel(productID);

                    // TimKen.DataEntity.Product pr = (TimKen.DataEntity.Product)(from r in dsproduct.Tables[0].AsEnumerable() where r["ProductID"].ToString() == productID.ToString() select r);

                    Project pro = new Project();
                    DataSet dsproduct = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, brandID, CategoryID, "", " and a.ProductID=" + productID, false, true, IndustryID);// ("ProductID=" + productID);//
                    foreach (DataRow itemd in dsproduct.Tables[0].Rows)
                    {
                        pro.ProjectXh = itemd["Name"].ToString();
                    }
                    pro.Date = DateTime.Now;// Convert.ToDateTime("2099-12-30");// pr.DateAdded;// DateTime.Now;
                    pro.Min = pr.MinMultiple;
                    pro.MinQuantitative = pr.MinNumber;
                    pro.Netweight = (float)pr.Weight;
                    pro.ProjectId = pr.ItemCode.Trim();// productID.ToString();
                    //pro.ProjectXh = pr.SalesUnit;// pr.CategoryID;
                    pro.Unitprice = GetProductBasePrice(productID).Price; //  GetProductBasePrice(productID).Price.Equals(0)
                    pro.TaxRate = (float)pr.TaxRate;
                    UserAccountManager uam = new UserAccountManager();
                    ProductManager pm = new ProductManager();
                    bool isAuthorizationed = pm.GetProductAuthorization(Convert.ToInt32(pro.ProjectId), uam.GetModel(CurrentUserName).CustomerID.Value);
                    ShopCartItem item = new ShopCartItem(pro, Convert.ToInt32(number),isAuthorizationed);
                    ShopCart.Add(item);

                    Alert(GetLangString("AddProductSuccessful"));
                }
            }
            else if (e.CommandName == "Favorite")
            {
                //如果用户未登陆，则跳转到注册页面
                if (CurrentUserName == null)
                    Response.Redirect("/User/Register.aspx");
                //TODO:添加逻辑
                TimKen.DataEntity.Favorite favorite = new TimKen.DataEntity.Favorite();
                favorite.DateAdded = DateTime.Now;
                favorite.ProductID = int.Parse(e.CommandArgument.ToString());
                favorite.UserName = CurrentUserName;
                frm.Add(favorite);
                Alert(GetLangString("FavoriteGood"));
            }
            else if (e.CommandName == "DownLoad")
            {
                int productID = int.Parse(e.CommandArgument.ToString());

                DataEntity.Product product = productManager.GetModel(productID);

                if (string.IsNullOrEmpty(product.IntroDocFiles))
                {
                    Alert("NotFoundFile");
                    return;
                }
                try
                {
                    string path = UploadFilePathForProduct + product.IntroDocFiles;
                    string filename = System.IO.Path.GetFileName(product.IntroDocFiles);

                    if (System.IO.File.Exists(Server.MapPath(path)))
                    {                      
                        string filePath = Server.MapPath(path);//路径 

                        //以字符流的形式下载文件 
                        FileStream fs = new FileStream(filePath, FileMode.Open);
                        byte[] bytes = new byte[(int)fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();
                        Response.ContentType = "application/octet-stream";
                        //通知浏览器下载文件而不是打开 
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        Response.End();
                    }
                    else
                    {
                        Alert(GetLangString("NotFoundFile"));
                    }
                }
                catch
                {
                    Response.Redirect("/Error.aspx");
                }
            }
        }
    }
}